package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean save = categoryService.save(category);
        log.info("category==="+category.toString());
        if (save){
            return R.success("添加分类成功");
        }else{
            return R.error("新增分类失败");
        }

    }


    /**
     * 分页查询操作
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> selectByPage(int page,int pageSize){
        //首先要设置分页拦截器
        //设置分页构造器
        Page<Category> pageInfo=new Page<>(page,pageSize);
        //设置条件过滤器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        //根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);
        if (pageInfo!=null){
            return R.success(pageInfo);
        }else{
            return R.error("分页失败");
        }
    }

    /**
     * 根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){

        boolean b = categoryService.remove(ids);
        if (b){
            return R.success("删除成功");
        }else{
            return R.error("该分类中包含了菜品或者套餐，不能删除");
        }

    }

    /**
     * 更新分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        //这里本来还要设置修改人和修改时间的，但是我们设置了公共字段自动填充
        boolean b = categoryService.updateById(category);
        if (b){
            return R.success("信息修改成功");
        }else{
            return R.error("信息修改失败");
        }
    }

    /**
     * 根据type查询分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //设置查询条件
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(category.getType()!=null,Category::getType,1);
        List<Category> list = categoryService.list(queryWrapper);
        if (list!=null){
            return R.success(list);
        }else {
            return R.error("查询分类失败");
        }

    }
}
